package com.changgou.controller;

import com.changgou.file.pojo.FastDFSFile;
import com.changgou.util.FastDFSUtil;
import entity.Result;
import entity.StatusCode;
import org.csource.common.MyException;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/upload")
@CrossOrigin  //跨域
public class FileUploadController {
    //文件上传
    @PostMapping
    public Result upload(@RequestParam(value = "file") MultipartFile file) throws IOException, MyException { //MultipartFile文件上传；RequestParam接收前端传过来的一个参数
//封装文件信息
        FastDFSFile fastDFSFile = new FastDFSFile(file.getOriginalFilename(), //文件名字
                file.getBytes(),//文件字节数组
                StringUtils.getFilenameExtension(file.getOriginalFilename()//获取文件扩展名)
                ));
        //调用FastDFSUtil工具类将文件传入到FastDFS中去
        String[] uploads = FastDFSUtil.upload(fastDFSFile);
        String url = FastDFSUtil.getTrackerInfo()+"/"+uploads[0]+"/"+uploads[1];
        return new Result(true, StatusCode.OK,"上传成功！",url);
    }
}
